package com.djf.eg.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.djf.eg.auth.DCryptography;
import com.djf.eg.dao.UserInfoDao;
import com.djf.eg.entity.SysRole;
import com.djf.eg.entity.UserInfo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

@Service
public class UserService {
	
	@Autowired
	UserInfoDao userDao;
	
	public Page<UserInfo> getUsers(int pageNum, int pageSize) {
		PageHelper.startPage(pageNum, pageSize);
		return userDao.getRolesByPage();
	}
	
	public List<UserInfo> getAllUsers() {
		return userDao.getAllUsers();
	}
	
	public UserInfo findByUsername(String username) {
		List<UserInfo> userList = userDao.getUserByUsername(username);
		return userList==null?null:userList.get(0);
	}
	
	public UserInfo register(String username, String password) {
		String encryptedPassword = DCryptography.encryptPassword(password, username);
		UserInfo userInfo = new UserInfo();
		userInfo.setUsername(username);
		userInfo.setPassword(encryptedPassword);
		userDao.addUser(userInfo);
		return userInfo;
	}
	
	@Transactional
	public void addUser(UserInfo user) {
		String encryptedPassword = DCryptography.encryptPassword(user.getPassword(), user.getUsername());
		user.setPassword(encryptedPassword);
		userDao.addUser(user);
		for (SysRole role : user.getRoles()) {
			userDao.addUserRole(user.getId(), role.getId());
		}
	}
	
	@Transactional
	public void updateUser(UserInfo user) {
		if (user.getPassword()==null || user.getPassword().equals("")) {
			user.setPassword(null);
		} else {
			String encryptedPassword = DCryptography.encryptPassword(user.getPassword(), user.getUsername());
			user.setPassword(encryptedPassword);
		}
		userDao.deleteUserRoles(user.getId());
		for (SysRole role : user.getRoles()) {
			userDao.addUserRole(user.getId(), role.getId());
		}
		userDao.updateUser(user);
	}
	
	@Transactional
	public void deleteUser(int userId) {
		userDao.deleteUserRoles(userId);
		userDao.deleteUser(userId);
	}
	
	
}
